package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

//菜品管理
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

//    @Autowired
//    private SetmealDishService setmealDishService;

    @Autowired
    private RedisTemplate redisTemplate;

    //新增菜品
    @CachePut(value = "dish_cache", key = "'dish_'+dishDto.categoryId")
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        //redisTemplate.delete("dish_*");
        return R.success("新增菜品成功");
    }

    //菜品分页查询
    @GetMapping("/page")
    public R<Page> page(@RequestParam Map map){
        //构造分页构造器对象
        Page<Dish> page = new Page<>(Long.parseLong((String)map.get("page")),Long.parseLong((String)map.get("pageSize")));
        Page<DishDto> dishDtoPage = new Page<>();
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(map.get("name") != null,Dish::getName,map.get("name"));
        lqw.orderByDesc(Dish::getUpdateTime);
        //分页查询
        dishService.page(page,lqw);
        //对象拷贝
        BeanUtils.copyProperties(page,dishDtoPage,"records");
        List<Dish> records = page.getRecords();
        List<DishDto> list = records.stream().map((item) -> {

            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    //修改菜品数据

    @GetMapping("/{id}")
    public R<DishDto> getDishId(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @CacheEvict(value = "dish_cache",key = "'dish_'+#dishDto.categoryId")
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        //Long dishId = dishDto.getId();
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }

    //批量删除
    @CacheEvict(value = "dish_cache",key = "#ids") //#id 代表变量名为id的参数
    @DeleteMapping
    public R<String> deleteDish(@RequestParam List<Long> ids){
        System.out.println(ids);
        dishService.removeByIds(ids);
        return R.success("删除成功");
    }

    //起售/停售 批量起售/批量停售
    @PostMapping("/status/{status}")
    public R<String> saleDish(@PathVariable Integer status,@RequestParam List<Long> ids){
        LambdaUpdateWrapper<Dish> lqw = new LambdaUpdateWrapper<>();
        lqw.set(Dish::getStatus,status);
        lqw.in(Dish::getId,ids);
        dishService.update(lqw);
//        for (Long id : ids) {
//            Dish dish = new Dish();
//            dish.setId(id);
//            dish.setStatus(status);
//            dishService.updateById(dish);
//        }
        return R.success("操作成功");
    }

    //根据分类id查询该分类下的所有菜品集合
//    @GetMapping("/list")
//    public R<List<Dish>> getDishById(Dish dish){
//        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//        lqw.eq(Dish::getStatus,1);
//        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> dishList = dishService.list(lqw);
//        return R.success(dishList);
//    }

    //修改根据分类id查询该分类下的所有菜品集合

    @GetMapping("/list")
    @Cacheable(value = "dish_cache",key = "'dish_'+#dish.categoryId")
    public R<List<DishDto>> getDishById(Dish dish) {
        /*String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        List<DishDto> dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos != null) {
            return R.success(dishDtos);
        }*/
            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
            lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
            lqw.eq(Dish::getStatus, 1);
            lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
            List<Dish> dishList = dishService.list(lqw);
            List<DishDto> dishDtos = new ArrayList<>();
            //将dish对象转变为dishDto对象
            for (Dish dish1 : dishList) {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(dish1, dishDto);
                LambdaUpdateWrapper<DishFlavor> lqw2 = new LambdaUpdateWrapper<>();
                lqw2.eq(DishFlavor::getDishId, dish1.getId());
                List<DishFlavor> flavors = dishFlavorService.list(lqw2);
                dishDto.setFlavors(flavors);
                dishDtos.add(dishDto);
            }
            //将数据库查到的数据缓存到redis中
        //redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);
            return R.success(dishDtos);
        }
    //}
}
